//
//  CTLoginVC.m
//  digitalCurrency
//
//  Created by 默认账户 on 2019/5/31.
//  Copyright © 2019 XinHuoKeJi. All rights reserved.
//

#import "CTLoginVC.h"
#import "YLNavigationController.h"
#import "countryViewController.h"
#import "MSLoginCell.h"
#import "MSPasswordCell.h"
#import "CTForgetPassWordVC.h"
#import "YLTabBarController.h"
#import "CTRegisterVC.h"
#import "CTLanguageVC.h"
#import "MSRegisterCell.h"
#import "LoginNetManager.h"
@interface CTLoginVC ()
{
    UILabel *leftTitleLB;
}
@property (nonatomic, copy) NSArray *placeHolders;

@property (nonatomic, strong) UIButton *commitBtn;
@property (nonatomic, strong) UIButton *forgetPwdBtn;
 @property (nonatomic, strong) UIButton *regist;
    
@property (nonatomic, strong) UIButton *countryBtn;
@property (nonatomic, strong) UITextField *loginTF;
@property (nonatomic, strong) UITextField *passwordTF;

@property(nonatomic,assign)NSInteger sqliteFlag;//判断是否存入
@property(nonatomic,copy)NSString *dbPath;//存入数据库的路径

@end

@implementation CTLoginVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        _placeHolders = @[@"手机号",@"请输入8-20位数字与字母结合的密码"];
    }
    return self;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
       return UIStatusBarStyleDefault;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubview];
//    [self setLanguageView];

    [self.view addSubview:self.tableView];
    self.tableView.separatorColor = [UIColor whiteColor];
    self.tableView.rowHeight = 65;
    [self.tableView registerClass:[MSRegisterCell class] forCellReuseIdentifier:@"registerCell"];
    [self.tableView registerClass:[MSPasswordCell class] forCellReuseIdentifier:@"passwordCell"];
    
    [self.view addSubview:self.commitBtn];
    [self.view addSubview:self.forgetPwdBtn];
    [self.view addSubview:self.regist];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    CGFloat statusH = kStatusBarHeight;

    CGRect rect = self.view.frame;
    rect.size.height = 130;
    rect.origin.y    = statusH +180;
    self.tableView.frame = rect;
    
    [self.forgetPwdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
       make.top.mas_equalTo(self.tableView.mas_bottom).offset(130);
        make.right.mas_equalTo(-46);
    }];
    
    [self.commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tableView.mas_bottom).offset(68);
        make.left.mas_equalTo(23);
        make.right.mas_equalTo(-23);
        make.height.mas_equalTo(44);
    }];
//    [ToolUtil view:self.commitBtn gradineViewOne:self.commitBtn.bounds colorOne:[UIColor colorWithHEX:maincolor] colorTwo:[UIColor colorWithHEX:mainGradientColor]];

    [self.regist mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(leftTitleLB);
        make.left.mas_equalTo(leftTitleLB.mas_right);
    }];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,40,0,40)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,40,0,40)];
    }
    
}

- (void)setLanguageView{
    
    UIButton *languageBtn = [[UIButton alloc]init];
    [self.view addSubview:languageBtn];
    [languageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(0);
        make.top.equalTo(SafeAreaNavTopHeight+20);
        make.height.equalTo(40);
        make.width.equalTo(60);
    }];
    [languageBtn setImage:ImageName(@"fanyi") forState:UIControlStateNormal];
    [languageBtn addTarget:self action:@selector(languageBtnAct) forControlEvents:UIControlEventTouchUpInside];
}

- (void)languageBtnAct{
    CTLanguageVC *language = [[CTLanguageVC alloc] init];
    language.isLoginStr = @"1";
    [self.navigationController pushViewController:language animated:YES];
}
    
- (void)registerUser {
    
    CTRegisterVC *vc = [[CTRegisterVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)forgetPwdClick {
    
    CTForgetPassWordVC *vc = [[CTForgetPassWordVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
    
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _placeHolders.count;
}
    
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row) {
        MSPasswordCell *cell = [MSPasswordCell createTableView:tableView];
        self.passwordTF  = cell.textField;
        cell.editingBlock = ^(NSString * _Nonnull text,NSInteger textLength) {
            if (textLength >= 8) {
                self.commitBtn.enabled = YES;
            }
            else {
                self.commitBtn.enabled = NO;
            }
        };
        
        return cell;
    }
    else {
        MSRegisterCell *cell = [MSRegisterCell createTableView:tableView];
        self.loginTF    = cell.textField;
        self.countryBtn = cell.selectedCountryBtn;
//        @weakify(self);
        [[cell.selectedCountryBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
//            @strongify(self);
//            [self selectCountry];
        }];
        return cell;
        
//        MSLoginCell *cell = [MSLoginCell createTableView:tableView];
//        self.loginTF      = cell.textField;
//        return cell;
    }
}
   
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,40,0,40)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,40,0,40)];
    }
}

-(void)selectCountry {
    countryViewController *countryVC = [[countryViewController alloc]init];
    countryVC.hidesBottomBarWhenPushed=YES;
    countryVC.returnValueBlock = ^(countryModel *model){
        NSLog(@"zhName:%@",model.zhName);
        [self.countryBtn setTitle:[NSString stringWithFormat:@"+%@",model.areaCode] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:self.countryBtn.titleLabel.text forKey:@"countrycode"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    };
    YLNavigationController *nav = [[YLNavigationController alloc] initWithRootViewController:countryVC];
    [self presentViewController:nav animated:YES completion:nil];
}
    
- (void)commitClick {
    
    [self.loginTF resignFirstResponder];
    [self.passwordTF resignFirstResponder];
    
    if ([NSString stringIsNull:self.loginTF.text]) {
        [self.view makeToast:LocalizationKey(@"inputMobileEmail") duration:1.5 position:CSToastPositionCenter];
        return ;
    }
    if ([NSString stringIsNull:self.passwordTF.text]) {
        [self.view makeToast:LocalizationKey(@"inputLoginPassword") duration:1.5 position:CSToastPositionCenter];
        return ;
    }
    
    if (![ToolUtil matchPassword:self.passwordTF.text]) {
        [self.view makeToast:NSLocalizedStringFromTableInBundle(@"Enter a password combining 8-20 digits and letters", @"English", [ChangeLanguage bundle], nil) duration:1.5 position:CSToastPositionTop];
        return ;
    }
    
    [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
    
    NSMutableDictionary *codeDic = [NSMutableDictionary dictionary];
    [LoginNetManager getLoginForPhone:self.loginTF.text withpassword:self.passwordTF.text withcode:@"86" withG3Result:codeDic CompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        if ([resPonseObj[@"code"] integerValue] == 0) {
            [YLUserInfo getuserInfoWithDic:resPonseObj[@"data"]];//存储登录信息
            [keychianTool saveToKeychainWithUserName:self.loginTF.text withPassword:self.passwordTF.text];
                
            NSString *executableFile = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleExecutableKey];//获取项目名称
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:[YLUserInfo shareUserInfo].token forKey:executableFile];
            [defaults setObject:self.loginTF.text forKey:@"username"];
            [defaults synchronize];
            
            YLTabBarController *SectionTabbar = [[YLTabBarController alloc] init];
            APPLICATION.window.rootViewController = SectionTabbar;
            
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [APPLICATION.window makeToast:resPonseObj[@"message"] duration:1.5 position:CSToastPositionCenter];
            });
        }
    }];
}
    
    //MARK:--存入数据库
-(void)saveToSqliteData{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [doc stringByAppendingPathComponent:@"user.sqlite"];
    self.dbPath = path;
    [self createTable];
}
    // 建表
- (void)createTable {
    //NSLog(@"%s", __func__);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:self.dbPath] == NO) {
        FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
        if ([db open]) {
            NSString *sql = @"CREATE TABLE 'User' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL , 'name' VARCHAR(30), 'password' VARCHAR(30))";
            BOOL res = [db executeUpdate:sql];
            if (!res) {
                NSLog(@"error when creating db table");
            } else {
                // NSLog(@"success to creating db table");
                [self insertData];
            }
            [db close];
        } else {
            NSLog(@"error when open db");
        }
    }else{
        [self queryData];
    }
}
    // 查询数据
- (void)queryData {
    // NSLog(@"%s", __func__);
    
    FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
    if ([db open]) {
        NSString *sql = @"select *from user";
        FMResultSet *rs = [db executeQuery:sql];
        while ([rs next]) {
            // int userId = [rs intForColumn:@"id"];
            NSString *name = [rs stringForColumn:@"name"];
            // NSString *pass = [rs stringForColumn:@"password"];
            //NSLog(@"user id = %d, name = %@, pass = %@", userId, name, pass);
            if ([name isEqualToString:self.loginTF.text]) {
                self.sqliteFlag = YES;
            }
        }
        if (self.sqliteFlag == NO) {
            [self insertData];
        }
        [db close];
    }
}
    // 插入数据
- (void)insertData {
    FMDatabase *db = [FMDatabase databaseWithPath:self.dbPath];
    if ([db open]) {
        
        NSString *sql = @"insert into user (name, password) values(?, ?) ";
        NSString *name = self.loginTF.text;
        NSString *password = self.passwordTF.text;
        BOOL res = [db executeUpdate:sql, name, password];
        if (!res) {
            NSLog(@"error to insert data");
        } else {
            //NSLog(@"success to insert data");
        }
        [db close];
    }
}
    
- (UIButton *)commitBtn {
    if (!_commitBtn) {
        _commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _commitBtn.layer.cornerRadius  = 5.0;
        _commitBtn.layer.masksToBounds = YES;
        _commitBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        _commitBtn.backgroundColor = [UIColor colorWithHEX:maincolor];
        [_commitBtn setTitle:LocalizationKey(@"login") forState:UIControlStateNormal];
        [_commitBtn addTarget:self action:@selector(commitClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _commitBtn;
}
    
- (UIButton *)forgetPwdBtn {
    if (!_forgetPwdBtn) {
        _forgetPwdBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_forgetPwdBtn setTitle:LocalizationKey(@"Forget password") forState:UIControlStateNormal];
        [_forgetPwdBtn setTitleColor:tThreeColor forState:UIControlStateNormal];
        _forgetPwdBtn.titleLabel.font = kFont(14);
        [_forgetPwdBtn addTarget:self action:@selector(forgetPwdClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _forgetPwdBtn;
}
 
- (UIButton *)regist {
    if (!_regist) {
        _regist = [UIButton buttonWithType:UIButtonTypeSystem];
        [_regist setTitle:LocalizationKey(@"New user registration") forState:UIControlStateNormal];
        [_regist setTitleColor:[UIColor colorWithHEX:maincolor] forState:UIControlStateNormal];
        [_regist addTarget:self action:@selector(registerUser) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _regist;
}
    
- (void)addSubview {
    UILabel *label = [[UILabel alloc] init];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:LocalizationKey(@"Welcome to Compass") attributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Semibold" size:36],NSForegroundColorAttributeName: tThreeColor}];
    label.attributedText = string;
    [self.view addSubview:label];
    CGFloat statusH = kStatusBarHeight;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(statusH + 69);
        make.left.mas_equalTo(33);
    }];
    
    leftTitleLB = [[UILabel alloc]init];
    [self.view addSubview:leftTitleLB];
    [leftTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label.mas_left);
        make.top.equalTo(label.mas_bottom).offset(16);
    }];
    leftTitleLB.font = kFont(15);
    leftTitleLB.textColor = tSixColor;
    leftTitleLB.text = LocalizationKey(@"欢迎登录，若无账号");
}

@end
